import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import { REFRESH_SERIALS, REFRESH_SERIAL, REFRESH_TOP_SERIALS, REFRESH_PAGEABLE_SERIALS } from '../constant/action-type'
import {message} from 'antd'

const refreshSerials = data => ({
  type: REFRESH_SERIALS,
  data
})

const refreshTopSerials = data => ({
  type: REFRESH_TOP_SERIALS,
  data
})

const refreshPageableSerials = data => ({
  type: REFRESH_PAGEABLE_SERIALS,
  data
})

const refreshSerial = data => ({
  type: REFRESH_SERIAL,
  data
})

export const getMySerials = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/serials/my`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshSerials(res.body))
      }
    })()
  }
}


export const getSerialPageable = (current = 1) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/serials/pageable?page=${--current}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshPageableSerials(res.body))
      }
    })()
  }
}
export const getTopSerials = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/serials/top`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshTopSerials(res.body))
      }
    })()
  }
}
export const getMySubscriptionSerials = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/serials/users/subscriptions`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshSerials(res.body))
      }
    })()
  }
}

export const deleteSerial = (id) => {
  return dispatch => {
    (async () => {
      const res = await request.del(`./api/serials/${id}`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('删除成功')
        dispatch(getMySerials())
      }
    })()
  }
}

export const createSerial = (serial,callback) => {
  return () => {
    (async () => {
      const res = await request.post(`./api/serials`, serial)
      if (res.status === HTTP_CODE.CREATED) {
        message.success('创建成功')
        callback()
      }
    })()
  }
}

export const getSerial = id => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/serials/${id}`)
      if (res.status === HTTP_CODE.OK) {
        console.log(res.body)
        dispatch(refreshSerial(res.body))
      }
    })()
  }
}

export const editSerial = (id, serial) => {
  return () => {
    (async () => {
      const res = await request.update(`./api/serials/${id}`, serial)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('编辑成功')
      }
    })()
  }
}

export const removeVideoFromSerial = (serialId, videoId) => {
  return dispatch => {
    (async () => {
      const res = await request.update(`./api/serials/video/${videoId}`, videoId)
      if (res.status === HTTP_CODE.OK) {
        message.success('移除成功')
        dispatch(getSerial(serialId))
      }
    })()
  }
}
